<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\TimeModel;
use buwang\util\Http;
use app\manage\model\Admin;
use app\manage\model\Member;
use buwang\util\Caches;
use itbdw\Ip\IpLocation;

class SysLog extends TimeModel
{

    protected $name = "sys_log";

    protected $deleteTime = false;

    protected static $ip_city_api_url = "http://ip.ws.126.net/ipquery?ip=@ip@";

    /**管理员
     * @return mixed
     */
    public function admin()
    {
        return $this->belongsTo('\app\manage\model\Admin', 'admin_id', 'id');
    }

    /**租户
     * @return mixed
     */
    public function member()
    {
        return $this->belongsTo('\app\manage\model\Member', 'member_id', 'id');
    }

    /**用户
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo('\app\common\model\User', 'user_id', 'id');
    }

    public function getAdminList()
    {
        return \app\manage\model\Admin::column('nickname', 'id');
    }

    public function getScopesList()
    {
        return ['admin' => '总后台', 'member' => '租户后台', 'mini_program' => '小程序', 'h5' => 'h5', 'app' => 'app', 'official' => '公众号',];
    }

    /**
     * 得到总后台登录日志
     */
    public static function getAdminLoginInfo($id, $page = 1, $limit = 10, $where = [], $sort = 'add_time desc')
    {
        $admin = Admin::find($id);
        if (!$admin) return [];
        $list = self::where($where)->where('path', '/manage/admin.Index/login')->where(function ($query)use($admin){
            $query->where('param', 'like', "%username\":\"{$admin['username']}\",%")->whereOr('param', 'like', "%username\":\"{$admin['mobile']}\"%")
                ->whereOr('param', 'like', "%mobile\":\"{$admin['username']}\"%")->whereOr('param', 'like', "%mobile\":\"{$admin['mobile']}\"%");
        })->page($page, $limit)->order($sort)->select()->toArray();
        $data = [];
        foreach ($list as &$value) {
            $value['name'] = $admin['username'];
            if(!$value['city_name']){
                $value['city_name'] = '';
                $city = self::getCityByIp($value['ip']);
                if($city){
                    $value['city_name'] = $city['country'] . '  ' . $city['regionName'] . '  ' . $city['city'] . '  ' . $city['zip'];
                    $data[] = [
                        'id'=>$value['id'],
                        'city_name'=>$value['city_name'],
                    ];
                }
            }
            $value['add_time_date'] = date('Y-m-d H:i:s', $value['add_time']);
        }
        if($data){
            $self = new self;
            $self->saveAll($data);
        }
        return $list;
    }


    /**
     * 得到租户登录日志
     */
    public static function getMemberLoginInfo($id, $page = 1, $limit = 10, $where = [], $sort = 'add_time desc')
    {
        $admin = Member::find($id);
        if (!$admin) return [];
        $list = self::where($where)->where('path', '/manage/member.Index/login')->where(function ($query)use($admin){
            $query->where('param', 'like', "%username\":\"{$admin['username']}\",%")->whereOr('param', 'like', "%username\":\"{$admin['mobile']}\"%")
                ->whereOr('param', 'like', "%mobile\":\"{$admin['username']}\"%")->whereOr('param', 'like', "%mobile\":\"{$admin['mobile']}\"%");;
        })->page($page, $limit)->order($sort)->select()->toArray();
        $data = [];
        foreach ($list as &$value) {
            $value['name'] = $admin['username'];
            if(!$value['city_name']){
                $value['city_name'] = '';
                $city = self::getCityByIp($value['ip']);
                if($city){
                    $value['city_name'] = $city['country'] . '  ' . $city['regionName'] . '  ' . $city['city'] . '  ' . $city['zip'];
                    $data[] = [
                        'id'=>$value['id'],
                        'city_name'=>$value['city_name'],
                    ];
                }
            }
            $value['add_time_date'] = date('Y-m-d H:i:s', $value['add_time']);
        }
        if($data){
            $self = new self;
            $self->saveAll($data);
        }



        return $list;
    }


    /**
     * 得到ip所在地址信息
     */
    public static function getCityByIp($ip = '')
    {
        $list = Caches::get('CITY_IP_'.$ip, function () use ($ip) {
//            $url = str_replace("@ip@", $ip, self::$ip_city_api_url);
//            $res = Http::getRequest($url);
//            var_dump($res);die;
//            return json_decode($res, true);
            $data  = IpLocation::getLocation($ip);
            if(isset($data['error'])){
                $city['country'] = '未查询出地址所在地';
                $city['regionName'] = '';
                $city['city'] = '';
                $city['zip'] = '';
            }else{
                $city['country'] = $data['country'];
                $city['regionName'] = $data['province'];
                $city['city'] = $data['city'];
                $city['zip'] = $data['isp'] ;
            }
            return $city;
        }, 300);
        return $list;
    }
}